<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="500" align-center>
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      class="form-wrap"
      label-width="120px"
    >
      <el-form-item label="指纹名称" prop="name">
        <ns-input v-model="formData.name" placeholder="请输入指纹名称" />
      </el-form-item>
      <!-- <el-form-item label="指纹类型" prop="type">
        <el-select placeholder="请选择指纹类型" v-model="formData.type" style="width: 100%">
          <el-option
            v-for="item in types"
            :label="item.name"
            :value="item.value"
            :key="item.value"
          />
        </el-select>
      </el-form-item> -->

      <el-form-item label="归属机构" prop="deptId">
        <el-cascader
          v-model="formData.deptId"
          clearable
          class="!w-full"
          placeholder="请选择归属机构"
          :options="options"
          :props="cascaderProps"
          value-on-clear="0"
          filterable
          :filter-method="sysFilterMethod"
        />
      </el-form-item>
      <el-form-item label="归属系统" prop="systemId">
        <el-cascader
          v-model="formData.systemId"
          placeholder="请选择归属系统"
          class="!w-full"
          :props="systemCascaderProps"
          value-on-clear=""
          :options="systemList"
          filterable
          clearable
          :filter-method="sysFilterMethod"
      /></el-form-item>
      <el-form-item label="数据保护标准" prop="standardId">
        <el-select
          v-model="formData.standardId"
          clearable
          class="!w-full"
          placeholder="请选择数据保护标准"
          @change="templateChange"
        >
          <el-option
            v-for="item in markedTemplateInfo"
            :label="item.dataStandardName"
            :value="item.id"
            :key="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="classificationId">
        <el-cascader
          class="!w-full"
          v-model="formData.classificationId"
          placeholder="请选择分类"
          :props="classificationCascaderProps"
          :options="classificationList"
          filterable
          clearable
          @change="classChange"
        />
      </el-form-item>
      <el-form-item label="分级" prop="levelId">
        <el-select v-model="formData.levelId" clearable class="!w-full" placeholder="请选择分级">
          <el-option
            v-for="(level, levelIndex) in levelList"
            :key="levelIndex"
            :label="level.levelName"
            :value="level.levelCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="指纹文件" prop="file" v-if="formType === 'create'">
        <el-upload
          ref="uploadRef"
          v-model:file-list="fileList"
          :action="UPLOAD_URL"
          :headers="uploadHeaders"
          :on-error="submitFormError"
          :on-exceed="handleExceed"
          :on-change="onFileChange"
          :limit="1"
          :auto-upload="false"
          style="width: 100%"
        >
          <el-button type="primary">选择文件</el-button>
          <!-- <template #tip>
            <div class="el-upload__tip"> 仅支持上传格式为text/plain的文件 </div>
          </template> -->
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { sysFilterMethod } from '@/utils/selectFilter'
import { getSimpleDeptList } from '@/api/system/dept'
import { getSimpleSystemList } from '@/api/asset/taskManage'
import { dataStandardsPage } from '@/api/dataStandards/standards/index'
import { handleTree } from '@/utils/tree'
import { levelPage } from '@/api/strategyManage/level/index'
import { classificationTree } from '@/api/dataStandards/classification/index'
import type { FormInstance } from 'element-plus'
import {
  createFinger,
  updateFinger,
  getFinger,
  getFingerType
} from '@/api/develop/featureLibrary/fingerprint'
import { useUpload } from '../useUpload'
import type { UploadInstance, UploadRawFile } from 'element-plus'

const cascaderProps = ref({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
})
const systemCascaderProps = {
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
}
const classificationCascaderProps = ref({
  checkStrictly: true,
  label: 'cnName',
  value: 'id',
  children: 'children',
  emitPath: false
})

export type FormType = 'create' | 'update' | ''

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const dialogTitle = ref('') // 弹窗的标题

const uploadRef = ref<UploadInstance>()

const {
  uploadHeaders,
  UPLOAD_URL,
  fileList, // 文件列表
  handleExceed,
  submitFormError
} = useUpload(uploadRef)

const onFileChange = (e: any) => {
  formData.value.name = e.name
}

watch(
  fileList,
  (files) => {
    if (files.length > 0) {
      formData.value.file = files[0].raw
    } else {
      formData.value.file = undefined
    }
    formRef.value!.validateField('file')
  },
  {
    deep: true
  }
)

const formType = ref<FormType>('') // 表单的类型：create - 新增；update - 修改

const formData = ref({
  id: undefined,
  name: '',
  file: undefined as UploadRawFile | undefined,
  deptId: '0' as string | number,
  systemId: '',
  standardId: '',
  levelId: '' as string | number,
  classificationId: ''
})

const isRequired = computed(() => {
  return formData.value.deptId == '0' && !formData.value.systemId
})

const formRules = reactive({
  name: [{ required: true, message: '指纹名称不能为空', trigger: ['blur', 'change'] }],
  deptId: [{ required: isRequired, message: '归属机构不能为空', trigger: 'change' }],
  systemId: [{ required: isRequired, message: '归属系统不能为空', trigger: 'change' }],
  file: [{ required: true, message: '指纹文件不能为空', trigger: ['blur', 'change'] }],
  standardId: [{ required: true, message: '数据保护标准不能为空', trigger: ['blur', 'change'] }],
  levelId: [{ required: true, message: '分级不能为空', trigger: ['blur', 'change'] }],
  classificationId: [{ required: true, message: '分类不能为空', trigger: ['blur', 'change'] }]
})
const formRef = ref<FormInstance>() // 表单 Ref

/** 打开弹窗 */

const open = async (type: FormType, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type

  if (id) {
    formLoading.value = true
    try {
      const res = await getFinger(id)
      formData.value.id = res.id
      formData.value.name = res.name
      formData.value.deptId = (res.deptId && +res.deptId) || '0'
      formData.value.systemId = res.systemId || ''
      formData.value.standardId = res.standardId
      formData.value.levelId = (res.levelId && +res.levelId) || ''
      formData.value.classificationId = res.classificationId
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  await formRef.value?.validate()

  // 提交请求
  formLoading.value = true

  const formData_ = new FormData()

  for (const [key, value] of Object.entries(toRaw(formData.value))) {
    if (value) {
      if (key === 'file') {
        formData_.append(key, value as UploadRawFile)
      } else {
        formData_.append(key, '' + value)
      }
    }
  }
  try {
    let res
    if (formType.value === 'create') {
      res = await createFinger(formData_)
    } else {
      res = await updateFinger(formData_)
    }

    formType.value === 'create'
      ? message.success(t('common.createSuccess'))
      : message.success(t('common.updateSuccess'))
    closeDialog()
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

/** 重置表单 */
const resetForm = () => {
  formLoading.value = false

  formData.value = {
    id: undefined,
    name: '',
    file: undefined,
    deptId: '0',
    systemId: '',
    standardId: '',
    levelId: '',
    classificationId: ''
  }
  uploadRef.value && uploadRef.value.clearFiles()
  formRef.value?.resetFields()
  fileList.value = []
}

function closeDialog() {
  dialogVisible.value = false
}

watch(dialogVisible, (show) => {
  !show && resetForm()
})

const types = ref<
  {
    name: string
    value: string
  }[]
>([])

// /** 获取指纹类型 */
// async function getTypes() {
//   const res = await getFingerType()
//   types.value = Object.entries(res).map(([key, value]) => {
//     return {
//       name: value as string,
//       value: key
//     }
//   })
// }
// getTypes()

const systemList = ref()
const options = ref()
const markedTemplateInfo = ref()
const levelList = ref<any[]>([])
const getSystemList = async () => {
  const data = await getSimpleSystemList({})
  systemList.value = handleTree(data, 'id', 'pid')
}
const getDeptList = async () => {
  const data = await getSimpleDeptList()
  options.value = data
}
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  levelList.value = data
}

// 分类下拉
const classificationList = ref<any[]>([])
const getClassificationList = async () => {
  const data = await classificationTree({
    standardId: formData.value.standardId
  })
  // data[0].disabled = true
  classificationList.value = data
}

function templateChange() {
  getClassificationList()
}

function classChange(e) {
  const selectClass = findNodeById(classificationList.value, e)
  if (selectClass) {
    formData.value.levelId = selectClass.levelCode
  }
}

// 定义一个函数来递归查找具有特定ID的节点
function findNodeById(nodes, id) {
  // 遍历所有节点
  for (const node of nodes) {
    // 如果找到ID匹配的节点，直接返回它
    if (node.id === id) {
      return node
    }
    // 如果当前节点有子节点，递归查找
    if (node.children && node.children.length > 0) {
      const foundNode = findNodeById(node.children, id)
      if (foundNode) {
        return foundNode
      }
    }
  }
  // 如果没有找到，返回undefined
  return undefined
}

onMounted(() => {
  getSystemList()
  getDeptList()
  dataStandardsPage({ page: 1, pageSize: 10000, status: '1' }).then((res) => {
    markedTemplateInfo.value = res.data
  })
  getLevelList()
  // getClassificationList()
})
</script>
<style lang="scss" scoped></style>
